<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Http;
use think\Db;

use app\api\model\Joinpay;
use app\api\model\Leshuapay;
use app\api\model\Order;
use think\Exception;
use think\Request;

/**
 * 示例接口
 */
class Pays extends Base
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['index', 'test','getOrderStatus'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['test2'];

    // 在构造函数中应用中间件
    protected $middleware = [
        \app\api\middleware\AuthMiddleware::class
    ];

    public function index()
    {
        $params = $this->paramInfo;

        //如果存在已拉起的支付直接返回
        if ($params['pay_info']){

//            $oauthUrl = $this->repeatAuthorize($params);
//            $authData = [
//                'isoauth' => 1,
//                'url'       =>$oauthUrl
//            ];
            $this->success('返回成功', json_decode($params['pay_info'], true));
        }

        $ordersn        = $params['ordersn'];
        $price          = $params['price'];
        $paytype        = $params['paytype'];
        $callbackurl    = $params['callbackurl'];
        $nonce_str      = $params['nonce_str'];
        $title          = $params['title'];
        $appid          = $params['appid'] ?? '';
        $openid         = $params['openid'] ?? '';



        $where = [
            'pcl.paytype' => ['like', '%' . $paytype . '%'], // 使用 LIKE 查询
            'pcl.status'  => '正常',
        ];

        $payplatform = $params['payplatform'];
        $payPlatformInfo = Db('payPlatform')->where(['enname' => $payplatform])->find();
        if ($payPlatformInfo){
            $where['pcl.pay_platform_id'] = $payPlatformInfo['id'];
        }

        $platform = $params['platform'];
        $platformListsInfo = Db('platformLists')->where(['enname' => $platform])->find();
        if ($platformListsInfo['codetype'] == '独立支付'){
            $where['pcl.platform_lists_id'] = ['=', $platformListsInfo['id']];
            $codes = Db('payCodeLists')
                ->alias('pcl')
                ->field('pcl.*')
                ->join('payCodeArea pca', 'pcl.id = pca.pay_code_lists_id', 'LEFT')
                ->where($where)
                ->where('pca.province', $params['province'])
                ->where('pca.city', $params['city'])
                ->where('pcl.codetype', '=','1')
                ->orderRaw('pcl.money asc')
                ->find();

        }else{
            $codes = Db('payCodeLists')
                ->alias('pcl')
                ->field('pcl.*')
                ->join('payCodeArea pca', 'pcl.id = pca.pay_code_lists_id', 'LEFT')
                ->where(function ($query) use ($where, $params) {
                    $query->where($where)
                        ->where(function ($query) use ($params) {
                            $query->where('pcl.isarea', '0')
                                ->whereOr(function ($query) use ($params) {
                                    $query->where('pcl.isarea', '1')
                                        ->where('pca.province', $params['province'])
                                        ->where('pca.city', $params['city'])
                                    ;
                                });
                        });
                })
                ->orderRaw('pcl.money asc')
                ->find();
        }

        //可用商户号查询
        //1 需要查询通用状态  2 固定参数  3 同时查询是否满足区域条件区域

        if (!$codes){
            $this->error('未找到对应的支付信息');
        }


        $pay_platform_name = ucfirst($payPlatformInfo['enname']);

        $params['merchant_no']  = $codes['merchant_no'];
        $params['verifycode']   = $codes['verifycode'];
        $params['platform_name']= $platformListsInfo['name'];
        $params['platform_lists_id']= $platformListsInfo['id'];
        $params['pay_code_lists_id']= $codes['id'];

        if ($codes){
            //可以创建订单了
            $orderInstance = new Order();

            $orderId = $orderInstance->createOrder($params);
            $params['orderid'] = $orderId;

            $className = 'app\\api\\model\\' . $pay_platform_name; // 拼接完整命名空间路径
            if (class_exists($className)) {
                $instance = new $className();
                $result = $instance->getOrder($params);

                if ($result['code'] != 100 && $result['code'] != 10080002){
                    //关闭订单  关闭商户号 已关闭不再拉起
                    Db('payCodeLists')->where(['id' => $codes['id']])->update(['status' => '禁用', 'closereason' => $result['msg']]);

                    //更新订单状态
                    Db('orderLists')->where(['id' => $orderId])->update(['status' => '支付失败']);
                    $this->error($result['msg']);
                }

                //获取到的商户号保存的post内
                Db('orderPost')->where(['id' => $params['id']])->update(['pay_code_lists_id' => $codes['id'], 'pay_info' => json_encode($result['data'])]);

                $this->success('返回成功', $result['data']);
            }
        }

        $this->success('返回成功', $this->request->param());
    }

    //重定向跳转重复支付




}
